const { defineConfig } = require('@vue/cli-service')
const TerserPlugin = require('terser-webpack-plugin')

const isDevelopment = process.env.NODE_ENV === 'development'
const isProduction = process.env.NODE_ENV === 'production'

module.exports = defineConfig({
  transpileDependencies: true,
  productionSourceMap: false,
  // 启用 source maps 用于调试
  configureWebpack: config => {
    if (isDevelopment) {
      // 开发环境启用 source maps 用于调试
      config.devtool = 'eval-source-map'
      config.optimization = {
        ...config.optimization,
        splitChunks: {
          chunks: 'all'
        }
      }
    } else if (isProduction) {
      // 生产环境禁用 source maps
      config.devtool = false

      config.optimization = {
        ...config.optimization,
        minimize: true,
        minimizer: [
          new TerserPlugin({
            terserOptions: {
              compress: {
                drop_console: true, // 移除 console.log
                drop_debugger: true, // 移除 debugger
                pure_funcs: ['console.log', 'console.info'] // 移除指定函数
              },
              mangle: true, // 混淆变量名
              format: {
                comments: false // 移除注释
              }
            },
            extractComments: false // 不提取注释到单独文件
          })
        ],
        splitChunks: {
          chunks: 'all',
          cacheGroups: {
            vendor: {
              test: /[\\/]node_modules[\\/]/,
              name: 'vendors',
              chunks: 'all',
              priority: 10
            },
            common: {
              name: 'common',
              minChunks: 2,
              chunks: 'all',
              priority: 5
            }
          }
        }
      }
    }
  },
  // 或者使用 CSS source maps
  css: {
    sourceMap: isDevelopment
  },
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8081',
        changeOrigin: true
      }
    }
  },
  chainWebpack: config => {
    if (isProduction) {
      // 生产环境移除预加载和预获取
      config.plugins.delete('preload')
      config.plugins.delete('prefetch')
    }
  }
})
